package com.geostart.constructionland.system.service.impl;

import com.geostar.constructionland.common.entity.lockInfo.RedisInfoPage;
import com.geostar.constructionland.common.entity.lockInfo.RedisLockVo;
import com.geostar.constructionland.common.entity.response.ExtJsAjaxResponse;
import com.geostart.constructionland.system.mapper.JsydBpxxMapper;
import com.geostart.constructionland.system.service.RedisLockService;
import com.geostart.constructionland.system.util.RedisServiceUtil;
import com.geostart.constructionland.system.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author chengan
 * @description
 */
@Service
public class RedisLockServiceImpl implements RedisLockService {

    @Autowired
    RedisServiceUtil redisService;

    @Autowired
    JsydBpxxMapper jsydBpxxMapper;

    @Value("${spring.redis.key.prefix.token}")
    private String redisTokenPrefix;

    @Override
    public ExtJsAjaxResponse redisLockPage(int pageNo, int pageNum, String query_ajid, String query_xmmc) {
        ExtJsAjaxResponse extJsAjaxResponse = null;
        /**分页初始数据**/
        int initRow = (pageNo - 1) * pageNum;
        int endRow = initRow + pageNum;
        if (StringUtils.isEmpty(query_ajid) && StringUtils.isEmpty(query_xmmc)) {
            /**在redis中查找相关数据**/
            Set<String> patternedKeys = redisService.getPatternKey(redisTokenPrefix + "_*");
            /**防止第一次页面取的数据比总页数多**/
            if(pageNum > patternedKeys.size()){
                initRow = 0;
                endRow = patternedKeys.size();
            }
            List<String> linkedHashSetList = new ArrayList<>(patternedKeys);
            List<String> subList = linkedHashSetList.subList(initRow, Math.min(endRow,patternedKeys.size()));
            /**生成页面信息**/
            RedisInfoPage redisInfoPage = new RedisInfoPage();
            redisInfoPage.setTotal(patternedKeys.size());
            LinkedList<RedisLockVo> redisList = new LinkedList<>();
            subList.stream().forEach(elemntKey -> {
                RedisLockVo redisLockVo = new RedisLockVo();
                /**获取案卷id**/
                String ywid = elemntKey.split("_")[1];
                redisLockVo.setAjid(ywid);
                String elementValue = redisService.get(elemntKey);
                /**获取锁定时间**/
                String lockTimeStr = elementValue.substring(33, 52);
                redisLockVo.setLockTime(lockTimeStr);
                /**设置已锁时间**/
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long nowTime = System.currentTimeMillis();
                try {
                    redisLockVo.setLockExistTime(TimeUtils.millionSeconds2HMS(nowTime - simpleDateFormat.parse(lockTimeStr).getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                /**设置过期时间**/
                Long expire = redisService.getExpire(elemntKey);
                redisLockVo.setExpireTime(expire == -1 ?"锁为永久":TimeUtils.millionSeconds2HMS(expire));
                /**设置项目名称**/
                String xmmc = elementValue.substring(53, elementValue.length());
                if(xmmc.equals("流程信息保存")){
                    xmmc = "(流程信息锁)"+jsydBpxxMapper.getXmmcByYwid(ywid);
                }
                redisLockVo.setXmmc(xmmc);
                redisList.add(redisLockVo);
            });
            redisInfoPage.setRecords(redisList);
            extJsAjaxResponse = ExtJsAjaxResponse.createBySuccess(redisInfoPage);
        } else if(!StringUtils.isEmpty(query_ajid)){
            /**根据Ywid查询单条数据**/
            String value = redisService.get(redisTokenPrefix + "_" + query_ajid);
            if (!StringUtils.isEmpty(value)) {
                RedisInfoPage redisInfoPage = new RedisInfoPage();
                redisInfoPage.setTotal(1);
                LinkedList<RedisLockVo> redisList = new LinkedList<>();
                /**单条数据设置值**/
                RedisLockVo redisLockVo = new RedisLockVo();
                redisLockVo.setAjid(query_ajid);
                String lockTimeStr = value.substring(33, 52);
                redisLockVo.setLockTime(lockTimeStr);
                redisLockVo.setXmmc(value.substring(53, value.length()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long nowTime = System.currentTimeMillis();
                try {
                    redisLockVo.setLockExistTime(TimeUtils.millionSeconds2HMS(nowTime - simpleDateFormat.parse(lockTimeStr).getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Long expire = redisService.getExpire(redisTokenPrefix + "_" + query_ajid);
                redisLockVo.setExpireTime(TimeUtils.millionSeconds2HMS(expire));
                redisList.add(redisLockVo);
                redisInfoPage.setRecords(redisList);
                extJsAjaxResponse = ExtJsAjaxResponse.createBySuccess(redisInfoPage);
            }else{
                extJsAjaxResponse = extJsAjaxResponse.createBySuccess();
            }
        }else{
            /**根据项目名称模糊查询多条数据**/
            Set<String> patternedKeys = redisService.getPatternKey(redisTokenPrefix + "_*");
            RedisInfoPage redisInfoPage = new RedisInfoPage();
            LinkedList<RedisLockVo> redisList = new LinkedList<>();
            int num[]=new int[1];
            patternedKeys.stream().forEach(
                    elemntKey->{
                        String elementValue = redisService.get(elemntKey);
                        /**如果key的项目名称包含**/
                        if(elementValue.substring(53, elementValue.length()).contains(query_xmmc)){
                            num[0]++;
                            RedisLockVo redisLockVo = new RedisLockVo();
                            /**获取案卷id**/
                            String ywid = elemntKey.split("_")[1];
                            redisLockVo.setAjid(ywid);
                            elementValue = redisService.get(elemntKey);
                            /**获取锁定时间**/
                            String lockTimeStr = elementValue.substring(33, 52);
                            redisLockVo.setLockTime(lockTimeStr);
                            /**设置已锁时间**/
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            long nowTime = System.currentTimeMillis();
                            try {
                                redisLockVo.setLockExistTime(TimeUtils.millionSeconds2HMS(nowTime - simpleDateFormat.parse(lockTimeStr).getTime()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            /**设置过期时间**/
                            Long expire = redisService.getExpire(elemntKey);
                            redisLockVo.setExpireTime(expire == -1 ?"锁为永久":TimeUtils.millionSeconds2HMS(expire));
                            /**设置项目名称**/
                            String xmmc = elementValue.substring(53, elementValue.length());
                            if(xmmc.equals("流程信息保存")){
                                xmmc = "(流程信息锁)"+jsydBpxxMapper.getXmmcByYwid(ywid);
                            }
                            redisLockVo.setXmmc(xmmc);
                            redisList.add(redisLockVo);
                        }
                    }
            );
            /****将结果封装*****/
            redisInfoPage.setTotal(num[0]);
            redisInfoPage.setRecords(redisList);
            extJsAjaxResponse=ExtJsAjaxResponse.createBySuccess(redisInfoPage);
        }
        return extJsAjaxResponse;
    }
}
